$(document).ready(function() {

   // $('.selectpicker').selectpicker();
    $('input[name="VALOR"]').maskMoney({
        thousands: ".",
        decimal: ","});

    $('a,[add="tooltip"]').tooltip();

    $('a[role="confirm-buyer"]').confirmPayment({urlConfirm: url_site + 'administrativo/confirmPayment'});

    $('a[role="liberarNFE"]').confirmNFE();

    $('[role="info-nota"]').infoNFE({url: url_site + 'administrativo/infoNFE'});


    $('[role="upload"]').on('click', function(e) {
        e.preventDefault();
        $('.fileUpload').trigger('click');
    });




    $('form.form-upload-txt').submit(function(e) {

        var l = $('.fileUpload').val(),
                pt = /^[a-zA-Z0-9\.\-\_]/gi;
        if (!pt.test(l)) {
            e.preventDefault();
            alert('Atenção nenhum arquivo foi selecionado ou o nome do arquivo está inválido');
        }

    });



    $('.message-template').delay(5000).slideUp();

    $('body').on('click', 'a[rel="page-order"]', function() {

        var data = {}, order = $(this).attr('data-change'), dataOrder = {}, dataId = $(this).attr('data-id'), max = 0;
        $('table#datagrid-container-' + TabActive + ' tbody').find('tr').each(function(i) {
            var id = $(this).attr('row-id'), pos_atual = $(this).find('td').eq(2).text();
            order = parseInt(order, 10);
            pos_atual = parseInt(pos_atual, 10);
            data[pos_atual] = id;
            dataOrder[pos_atual] = id;
            if (order == pos_atual) {
                data[pos_atual] = dataId;
            }

            max += 1
        });
        var nOrder = {}, list = [];

        for (var i = 1; i <= max; i += 1) {
            list[i] = dataOrder[i];
            var id = data[i],
                    next = i < max ? i + 1 : max,
                    nextVal = dataOrder[next],
                    prev = i > 1 ? i - 1 : 1,
                    prevP = i > 2 ? i - 2 : 1,
                    prevVal = dataOrder[prev],
                    prevPVal = data[prevP],
                    prevId = data[prev], nextId = data[next];
            if (prevVal == id && id == prevId) {
                dataOrder[prev] = dataOrder[i];
                dataOrder[i] = prevVal;
            }





        }
        // console.log(dataOrder);
        for (var i in dataOrder) {
            nOrder[i] = {id: dataOrder[i], order: i};

        }



        $.ajax({
            url: url_site + '/administrativo/change_position_categoria',
            type: 'post',
            dataType: 'json',
            data: nOrder,
            success: function(data) {
                location.reload();

            }
        });



    });

    $('.inMessagePayment').delay(5000).slideUp(1000, function() {
        $(this).remove();
    });

    $('input[name="all[]"]').off('click').on('click', function() {
        var id = $(this).attr('data-id'), ArrayData = [], isChecked = $(this).prop('checked');
        if (isChecked === true) {
            $('input[name="id[' + id + '][]"]').each(function() {
                $(this).prop('checked', true);
            });
        }
        if (isChecked === false) {
            $('input[name="id[' + id + '][]"]').each(function() {
                $(this).prop('checked', false);
            });
        }
    });

    $('input[name="all[]"]').each(function() {
        var id = $(this).attr('data-id'),
                numRowsChecked = $('input[name="id[' + id + '][]"]:checked').size(),
                numRowsAllInputs = $('input[name="id[' + id + '][]"]').size();

        if (numRowsChecked == numRowsAllInputs) {
            $(this).prop('checked', true);
        }






    });



    $('[role="free-lote"]').on('click', function() {

        var id = $(this).attr('data-id'),
                idLeilao = $(this).attr('data-id-leilao');

        var markup = '<div id="confirmJBoxDetails" class="confirmJBox" title="Informações para liberar lote">' +
                '<div class="form-group">' +
                form_open(url_site + '/administrativo/liberarLoteCondicional', 'id="formLiberarCondicional"') +
                form_hidden('id', id) +
                form_hidden('idLeilao', idLeilao) +
                form_label('Confirmar valor') +
                form_input('valor') +
                form_close() +
                '</div>' +
                '</div>',
                self = this;



        $('#confirmJBoxDetails').remove();
        $(markup).appendTo('body').dialog({
            MinHeight: 250,
            resizable: false,
            modal: true,
            dialogClass: 'confirmJBox',
            buttons:
                    [
                        {
                            text: 'Confirmar',
                            click: function() {
                                var ival = $('input[name="valor"]').val(),
                                        pattern = /[0-9,\.]/gi;
                                if (pattern.test(ival) == false) {

                                    alert('O campo é obrigatório, e precisa de valores válidos. Ex(999 ou 999,00)');
                                } else {
                                    $('#formLiberarCondicional').submit();
                                }


                            },
                            class: 'btn btn-xs btn-info'
                        },
                        {
                            text: 'Cancelar',
                            click: function() {
                                $(this).dialog('close');


                            },
                            class: 'btn btn-xs btn-danger'
                        }

                    ]


        });


    });


});


(function($, window, document, undefined) {


    var PluginName = 'confirmPayment',
            defaults = {
                message: 'Deseja realizar esse operação ?',
                urlConfirm: !1
            },
    initializePayment = false;

    function Plugin(element, options) {

        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._name = PluginName;

        this.initialize();
    }

    Plugin.prototype = {
        initialize: function() {
            var self = this, url = $(this.element).attr('href') ? $(this.element).attr('href') : ($(this.element).attr('url') ? $(this.element).attr('url') : false);
            if ($(this.element).attr('message')) {
                self.options.message = $(this.element).attr('message');
            }
            $(this.element).on('click', function(ev) {
                ev.preventDefault();
                id = $(this).attr('data-id');
                if (self._existsLoteCondicional(id) === true) {
                    alert('Atenção existem lotes condicionais para serem liberados.');
                } else {
                    self._confirmBox(id);
                }

            });
        },
        _existsLoteCondicional: function(id) {

            var rows = $('[data-is-condicional="' + id + '"]').size();

            return rows > 0 ? true : false;

        },
        _confirmBox: function(id) {
            initializePayment = false
            var markup = '<div id="confirmJBox" class="confirmJBox" title="Sistema pergunta">' +
                    this.options.message
                    + '</div>',
                    self = this;

            $('#confirmJBox').remove();
            $(markup).appendTo('body').dialog({
                MinHeight: 150,
                resizable: false,
                modal: true,
                dialogClass: 'confirmJBox',
                buttons:
                        [
                            {
                                text: 'Confirmar',
                                click: function() {
                                    $(this).dialog('close');
                                    self._confirmBoxDetails(id);
                                },
                                class: 'btn btn-xs btn-info'
                            },
                            {
                                text: 'Cancelar',
                                click: function() {
                                    $(this).dialog('close');
                                },
                                class: 'btn btn-xs btn-danger'
                            }

                        ]


            });

        },
        _confirmBoxDetails: function(id) {

            var markup = '<div id="confirmJBoxDetails" class="confirmJBox" title="Informações de confirmação ">' +
                    '<div class="form-group">' +
                    form_label('Numero do Documento ') +
                    form_input('numero_document') +
                    '</div>' +
                    '</div>',
                    self = this;



            $('#confirmJBoxDetails').remove();
            $(markup).appendTo('body').dialog({
                MinHeight: 250,
                resizable: false,
                modal: true,
                dialogClass: 'confirmJBox',
                buttons:
                        [
                            {
                                text: 'Confirmar',
                                click: function() {
                                    //$(this).dialog('close');
                                    if (initializePayment === true) {
                                        self._showMessageLoadingNoFinishPayment();
                                    }
                                    if (initializePayment === false) {
                                        $ajax = self._ajaxConfirmPayment(id);

                                        $ajax.done(function() {
                                            location.reload();

                                        });

                                    }


                                },
                                class: 'btn btn-xs btn-info'
                            },
                            {
                                text: 'Cancelar',
                                click: function() {
                                    if (initializePayment === true) {
                                        self._showMessageLoadingNoFinishPayment();
                                    } else {
                                        $(this).dialog('close');
                                    }

                                },
                                class: 'btn btn-xs btn-danger'
                            }

                        ]


            });

        },
        _ajaxConfirmPayment: function(id) {
            var tdata = {}, lotes = [];
            $('input[name="lotes[' + id + '][]"]').each(function() {
                lotes.push(this.value);
            });
            tdata.pid = id;
            tdata.lotes = lotes;
            tdata.num_doc = $('input[name="numero_document"]').val();
            initializePayment = true;
            return $.ajax({
                url: this.options.urlConfirm,
                type: 'post',
                //dataType:'json',
                data: tdata,
                beforeSend: function() {
                    $('#confirmJBoxDetails').html('<div class="grid-loading" ></div>');
                    $('#confirmJBoxDetails .grid-loading').show();
                }

            });
        },
        _showMessageLoadingNoFinishPayment: function() {
            $('#alertLoadingPaymentNoFinish').remove();
            $('<div id="alertLoadingPaymentNoFinish" class="alert alert-danger" style="position:fixed; z-index:30000; top:0px; left:0px; right:0px; width:100%; display:none; ">' +
                    'Aguarde enquando a operação de confirmação de pagamento é finalizada '
                    + '</div>').appendTo('body').slideDown().delay(4000).slideUp();
        }
    };



    $.fn[PluginName] = function(options) {

        return this.each(function() {

            if (!$.data(this, 'plugin_' + PluginName)) {
                $.data(this, 'plugin_' + PluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window);



///confirmNFE
(function($, window, document, undefined) {


    var PluginName = 'confirmNFE',
            defaults = {
                message: 'Deseja realizar esse operação ?',
                url: url_site + '/administrativo/saveNFE/'
            },
    initializeNFECreate = false;

    function Plugin(element, options) {

        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._name = PluginName;

        this.initialize();
    }

    Plugin.prototype = {
        initialize: function() {
            var self = this, url = $(this.element).attr('href') ? $(this.element).attr('href') : ($(this.element).attr('url') ? $(this.element).attr('url') : false);
            if ($(this.element).attr('message')) {
                self.options.message = $(this.element).attr('message');
            }
            $(this.element).on('click', function(ev) {
                ev.preventDefault();
                var id = $(this).attr('data-id'),
                        pcid = $('.bpid_' + id).attr('pcid');
                if (pcid > 0) {
                    self._confirmBox(url);
                } else {
                    self._boxNoPayment();

                }

            });
        },
        _confirmBox: function(url) {
            initializeNFECreate = false;
            var markup = '<div id="confirmJBoxNfe" class="confirmJBox" title="LIBERAÇÃO DE NOTA DE VENDA">' +
                    '<div class="grid-loading pull-right" style="margin-top:10px;"></div>'
                    + '</div>',
                    self = this;

            $('#confirmJBoxNfe').remove();
            $(markup).appendTo('body').dialog({
                height: 550,
                width: 700,
                zIndex: 30000,
                resizable: false,
                modal: true,
                dialogClass: 'confirmJBox',
                buttons:
                        [
                            {
                                text: 'Confirmar',
                                click: function() {
                                    // $(this).dialog('close');


                                    var ObjDialog = this;
                                    if (initializeNFECreate === false) {

                                        $ajax = self._ajaxCreateNfe();

                                        $ajax.done(function(data) {
                                            location.reload();

                                        });
                                    }




                                },
                                class: 'btn btn-xs btn-info'
                            },
                            {
                                text: 'Cancelar',
                                click: function() {
                                    $(this).dialog('close');
                                },
                                class: 'btn btn-xs btn-danger'
                            }

                        ]


            });

            $.ajax({
                url: url,
                beforeSend: function() {
                    $('.grid-loading').show();
                },
                success: function(data) {
                    $('#confirmJBoxNfe').html(data);

                    $('input[name="desconto"]').maskMoney({
                        thousands: '.',
                        decimal: ','
                    }).focusout(function() {

                        var ival = this.value !== '' ? this.value : 0.00;
                        ival = ival.replace('.', '');
                        ival = ival.replace(',', '.');
                        ival = parseFloat(ival),
                                sbtotal = parseFloat($('[data-stotal="yes"]').attr('data-value')),
                                taxa = parseFloat($('[data-taxa="yes"]').attr('data-value')),
                                comissao = parseFloat($('[data-comissao="yes"]').attr('data-value'))
                                ;
                        //if(ival !== 0.00 && ival != ''){


                        var total = (sbtotal + comissao + taxa) - ival;
                        $('[data-total="yes"]').text(number_format(total, 2, ',', '.'));

                        //}  

                    });
                }
            });


        },
        _boxNoPayment: function() {

            var markup = '<div id="confirmJBox" class="confirmJBox" title="Sistema informa">' +
                    '<div class="alert alert-danger">Para liberar a nota fiscal é precisso confirmar o pagamento </div>'
                    + '</div>',
                    self = this;

            $('#confirmJBox').remove();
            $(markup).appendTo('body').dialog({
                height: 180,
                width: 400,
                zIndex: 30000,
                resizable: false,
                modal: true,
                dialogClass: 'confirmJBox',
                buttons:
                        [
                            {
                                text: 'OK',
                                click: function() {
                                    $(this).dialog('close');


                                },
                                class: 'btn btn-xs btn-info'
                            }

                        ]


            });

        },
        _ajaxCreateNfe: function() {

            initializeNFECreate = true;
            var ival = $('input[name="desconto"]').val(), idata = {},
                    uid = $('input[name="desconto"]').attr('data-id'),
                    obs = $('textarea[name="nfe_observao"]').val(),
                    lotes = [];
            $('input[name="nfe_lotes[]"]').each(function() {

                lotes.push(this.value);
            });

            idata.d = ival;
            idata.uid = uid;
            idata.obs = obs;
            idata.lotes = lotes;
            idata.lid = $('input[name="lid"]').val();

            return  $.ajax({
                url: this.options.url,
                type: 'post',
                data: idata,
                beforeSend: function() {
                    $('#confirmJBoxNfe').html('<div class="grid-loading" ></div>');
                    $('#confirmJBoxNfe .grid-loading').show();
                }

            });




        }
    };



    $.fn[PluginName] = function(options) {

        return this.each(function() {

            if (!$.data(this, 'plugin_' + PluginName)) {
                $.data(this, 'plugin_' + PluginName, new Plugin(this, options));
            }
        });
    }

})(jQuery, window);


//nfeInfo
(function($, window, document, undefined) {


    var PluginName = 'infoNFE',
            defaults = {
                url: url_site + '/administrativo/saveNFE/',
                urlSave: url_site + '/administrativo/updateNFE/'
            },
    initializeNFESave = false;

    function Plugin(element, options) {

        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._name = PluginName;

        this.initialize();
    }

    Plugin.prototype = {
        initialize: function() {
            var self = this, url = $(this.element).attr('href') ? $(this.element).attr('href') : ($(this.element).attr('url') ? $(this.element).attr('url') : false);
            if ($(this.element).attr('message')) {
                self.options.message = $(this.element).attr('message');
            }
            $(this.element).on('click', function(ev) {
                ev.preventDefault();
                var id = $(this).attr('data-id');

                self._boxInfo(id);

            });
        },
        _boxInfo: function(id) {
            initializeNFESave = false;
            var markup = '<div id="confirmJBoxNfeInfo" class="confirmJBox" title="INFORMAÇÕES DA NOTA DE VENDA">' +
                    '<div class="grid-loading pull-right" style="margin-top:10px;"></div>'
                    + '</div>',
                    self = this;

            $('#confirmJBoxNfeInfo').remove();
            $(markup).appendTo('body').dialog({
                height: 250,
                width: 700,
                zIndex: 30000,
                resizable: false,
                modal: true,
                dialogClass: 'confirmJBox',
                buttons:
                        [
                            {
                                text: 'Gravar',
                                click: function() {
                                    // $(this).dialog('close');


                                    var ObjDialog = this;

                                    $ajax = self._ajaxSaveNFE(id);

                                    $ajax.done(function() {
                                        $(ObjDialog).dialog('close');
                                    });


                                },
                                class: 'btn btn-xs btn-info'
                            },
                            {
                                text: 'Cancelar',
                                click: function() {
                                    $(this).dialog('close');
                                },
                                class: 'btn btn-xs btn-danger'
                            }

                        ]


            });

            $.ajax({
                url: this.options.url,
                type: 'post',
                data: {id: id},
                beforeSend: function() {
                    $('.grid-loading').show();
                },
                success: function(data) {
                    $('#confirmJBoxNfeInfo').html(data);

                    $('input[name="desconto"]').maskMoney({
                        thousands: '.',
                        decimal: ','
                    }).focusout(function() {



                    });
                }
            });


        },
        _ajaxSaveNFE: function(id) {

            initializeNFESave = true;
            var idata = {}
            $('#confirmJBoxNfeInfo').find('textarea,input[type="text"],input[type="hidden"]').each(function() {
                var iname = $(this).attr('name');
                idata[iname] = this.value;

            });
            idata.id = id;

            return  $.ajax({
                url: this.options.urlSave,
                type: 'post',
                data: idata,
                beforeSend: function() {
                    $('#confirmJBoxNfeInfo').html('<div class="grid-loading" ></div>');
                    $('#confirmJBoxNfeInfo .grid-loading').show();
                }

            });




        }
    };



    $.fn[PluginName] = function(options) {

        return this.each(function() {

            if (!$.data(this, 'plugin_' + PluginName)) {
                $.data(this, 'plugin_' + PluginName, new Plugin(this, options));
            }
        });
    }

})(jQuery, window);




function showCondicao(obj) {

    var id = $(obj).attr('data-id');
    $('div#condicao-' + id).slideToggle("slow");
    return false;
}
